<!-- 会员充值界面 -->
<template>
  <view class="page-container">
    <!-- 顶部余额显示区域 -->
    <view class="header-section">
      <view class="balance-info">
        <view class="balance-label">当前余额（元）</view>
        <view class="balance-amount">{{ fen2yuan(userWallet.balance || 0) }}</view>
      </view>
      <tui-button 
        width="180rpx" 
        height="64rpx" 
        :size="28" 
        type="white" 
        plain 
        shape="circle"
        @click="goToRechargeLog">
        充值记录
      </tui-button>
    </view>

    <!-- 充值表单卡片 -->
    <view class="recharge-section">
      <view class="recharge-card">
        <view class="card-title">充值金额</view>
        
        <!-- 金额输入区域 -->
        <view class="amount-input-area">
          <view class="currency-symbol">¥</view>
          <input 
            v-model="state.recharge_money" 
            type="digit" 
            placeholder="请输入充值金额"
            class="amount-input"
            placeholder-style="color: #CCCCCC; font-size: 32rpx;"
          />
        </view>
        
        <!-- 充值套餐选择 -->
        <view class="package-list">
          <view 
            class="package-item" 
            v-for="item in state.packageList" 
            :key="item.id"
            :class="{ 'package-active': state.recharge_money === fen2yuan(item.payPrice) }"
            @tap="onCard(item.payPrice)">
            <view class="package-amount">{{ fen2yuan(item.payPrice) }}元</view>
            <view v-if="item.bonusPrice" class="package-bonus">
              送{{ fen2yuan(item.bonusPrice) }}元
            </view>
          </view>
        </view>
        
        <!-- 确认充值按钮 -->
        <tui-button 
          width="100%" 
          height="96rpx" 
          :size="32" 
          type="primary" 
          shape="circle"
          @click="onConfirm">
          确认充值
        </tui-button>
      </view>
    </view>

    <!-- 支付方式选择弹窗 -->
    <t-pay-way 
      :show="showPayWay" 
      :sub-order="rechargeOrderInfo" 
      :order-info="rechargeOrderInfo"
      :balance="userWallet.balance || 0"
      @close="closePayWay"
      @confirm="handleConfirmPayment">
    </t-pay-way>
  </view>
</template>

<script>
import { fen2yuan } from '@/common/lib/priceUtil.js';
import tPayWay from '../components/views/t-pay-way/t-pay-way';

export default {
  components: {
    tPayWay
  },
  data() {
    return {
      showPayWay: false,
      rechargeOrderInfo: null,
      userWallet: {
        balance: 0
      },
      state: {
        recharge_money: '', // 输入的充值金额
        packageList: [],
      },
    }
  },
  onLoad() {
    // 获取钱包信息
    this.getWallet();
    // 获取充值套餐列表
    this.getRechargeTabs();
  },
  methods: {
    // 分转元
    fen2yuan(price) {
      if (!price && price !== 0) return '0.00';
      return (Number(price) / 100).toFixed(2);
    },
    // 获取钱包信息
    async getWallet() {
      try {
        const res = await this.$api.req("/pay/wallet/get", {}, "get", "JSON", false);
        if (res.code === 0) {
          this.userWallet = res.data || { balance: 0 };
        }
      } catch (error) {
        console.error('获取钱包信息失败', error);
      }
    },
    // 获得钱包充值套餐列表
    async getRechargeTabs() {
      try {
        const res = await this.$api.req("/pay/wallet-recharge-package/list", {}, "get", "JSON", false);
        if (res.code === 0) {
          this.state.packageList = res.data || [];
        }
      } catch (error) {
        console.error('获取充值套餐失败', error);
      }
    },
    // 点击卡片，选择充值金额
    onCard(payPrice) {
      this.state.recharge_money = this.fen2yuan(payPrice);
    },
    // 发起支付
    async onConfirm() {
      if (!this.state.recharge_money || parseFloat(this.state.recharge_money) <= 0) {
        uni.showToast({
          title: '请输入充值金额',
          icon: 'none'
        });
        return;
      }

      // 查找选中的套餐ID
      const selectedPackage = this.state.packageList.find(
        (item) => this.fen2yuan(item.payPrice) === this.state.recharge_money
      );

      const rechargeData = {
        packageId: selectedPackage ? selectedPackage.id : null,
        payPrice: parseFloat(this.state.recharge_money) * 100,
      };

      try {
        // 创建充值订单
        const res = await this.$api.req("/pay/wallet-recharge/create", rechargeData, "POST", "JSON", false);
        if (res.code !== 0) {
          uni.showToast({
            title: res.msg || '创建充值订单失败',
            icon: 'none'
          });
          return;
        }
        
        // 处理返回数据
        if (typeof res.data === 'number' || (typeof res.data === 'string' && !isNaN(res.data))) {
          this.rechargeOrderInfo = {
            id: Number(res.data),
            payOrderId: Number(res.data),
            payPrice: parseFloat(this.state.recharge_money) * 100
          };
        } else {
          this.rechargeOrderInfo = res.data;
        }
        
        // 显示支付弹窗
        this.showPayWay = true;
      } catch (error) {
        console.error('创建充值订单失败', error);
        uni.showToast({
          title: '创建充值订单失败，请重试',
          icon: 'none'
        });
      }
    },
    // 关闭支付弹窗
    closePayWay() {
      this.showPayWay = false;
    },
    // 支付成功回调
    handleConfirmPayment({ payMethod }) {
      this.showPayWay = false;
      
      if (payMethod === 'wechat') {
        uni.showToast({
          title: '充值成功',
          icon: 'success',
          duration: 2000
        });
        
        // 刷新钱包信息
        this.getWallet();
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    // 跳转到充值记录
    goToRechargeLog() {
      uni.navigateTo({
        url: '/subPackage2/rechargeLog/rechargeLog'
      });
    },
  }
}
</script>

<style lang="scss" scoped>
  /* Sheep UI 样式已移除，使用自定义样式 */

  .page-container {
    min-height: 100vh;
    background: #F8F8F8;
  }

  /* 顶部余额区域 - 白色背景，深色文字 */
  .header-section {
    padding: 40rpx 30rpx 60rpx;
    background: #FFFFFF;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;

    .balance-info {
      flex: 1;
    }

    .balance-label {
      font-size: 28rpx;
      font-weight: 400;
      color: #999999;
      margin-bottom: 20rpx;
    }

    .balance-amount {
      font-size: 64rpx;
      font-weight: 600;
      color: #333333;
      font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
    }
  }

  /* 充值表单区域 */
  .recharge-section {
    padding: 0 30rpx;
    margin-top: -50rpx;
    position: relative;
    z-index: 10;
  }

  .recharge-card {
    width: 100%;
    background: #FFFFFF;
    border-radius: 24rpx;
    padding: 50rpx 40rpx;
    box-sizing: border-box;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);

    .card-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
      margin-bottom: 40rpx;
    }

    /* 金额输入区域 */
    .amount-input-area {
      display: flex;
      align-items: center;
      padding-bottom: 30rpx;
      border-bottom: 2rpx solid #F0F0F0;
      margin-bottom: 40rpx;
    }

    .currency-symbol {
      font-size: 56rpx;
      font-weight: 600;
      color: #333333;
      margin-right: 20rpx;
      font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
    }

    .amount-input {
      flex: 1;
      font-size: 56rpx;
      font-weight: 600;
      color: #333333;
      font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
      height: 70rpx;
      line-height: 70rpx;
    }

    /* 充值套餐列表 */
    .package-list {
      display: flex;
      flex-wrap: wrap;
      margin: 40rpx 0 50rpx;
      gap: 20rpx;
    }

    .package-item {
      width: calc(33.33% - 14rpx);
      min-height: 160rpx;
      background: #FFFFFF;
      border: 2rpx solid #E8E8E8;
      border-radius: 16rpx;
      padding: 30rpx 20rpx;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: relative;
      transition: all 0.3s;
      cursor: pointer;

      &:active {
        transform: scale(0.96);
      }

      .package-amount {
        font-size: 36rpx;
        font-weight: 600;
        color: #333333;
        font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
        margin-bottom: 12rpx;
      }

      .package-bonus {
        font-size: 24rpx;
        font-weight: 500;
        color: var(--ui-BG-Main);
        background: rgba(102, 126, 234, 0.1);
        padding: 6rpx 16rpx;
        border-radius: 20rpx;
        white-space: nowrap;
      }
    }

    .package-active {
      background: #FFFFFF;
      border: 2rpx solid #EB0909;
      box-shadow: 0 0 0 2rpx rgba(235, 9, 9, 0.1);

      .package-amount {
        color: #333333;
      }

      .package-bonus {
        color: #EB0909;
        background: rgba(235, 9, 9, 0.1);
      }
    }

  }
</style>
